/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.hiddendanger.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.koron.audit.domain.Audit;
import com.koron.common.Excel;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.common.web.Util;
import com.koron.hiddendanger.domain.HiddenDangerDiscovery;
import com.koron.hiddendanger.domain.HiddenDangerRectification;
import com.koron.hiddendanger.service.api.HiddenDangerDiscoveryService;
import com.koron.safetytask.utils.BusinessCode;
import com.koron.system.annotation.Log;
import com.koron.system.discrete.BusinessManipulation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "hiddenDangerDiscovery", description = "隐患台账接口类")
@RestController
@RequestMapping("/hiddenDangerDiscovery")
public class HiddenDangerDiscoveryController {
    @Autowired
    private HiddenDangerDiscoveryService dangerDiscoveryService;
    private final static Logger logger = LoggerFactory.getLogger(HiddenDangerDiscoveryController.class);

    @Autowired
    private Util util;

    @ApiOperation("获取隐患台账列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userCode", value = "当前登录人code,pc不传，app必传字段", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "description", value = "隐患描述", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dangerType", value = "隐患分类", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dangerLevel", value = "隐患分级", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "corpCode", value = "水司code", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "gridCode", value = "网格结点code，隐患所在位置", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "checkUnit", value = "检查单位code", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "检查日期,查询开始日期", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "检查日期，查询结束日期", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "submitterCode", value = "发起人", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "隐患状态,0草稿，1待整改，2整改中，3超期未整改，4已关闭", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页数", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "mobile", value = "移动端隐患台账查询，1表示是", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "queryAll", value = "查询所有隐患台账，1表示是", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "keyword", value = "关键词", paramType = "query", dataType = "String")
    })
    @RequestMapping(value = "/list.htm", method = RequestMethod.POST)
    public MessageBean<DataBean<HiddenDangerDiscovery>> queryDangerByCondition(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String userCode, @RequestParam(required = false) final String description, @RequestParam(required = false) final String dangerType, @RequestParam(required = false) String  submitterCode,
                                                                               @RequestParam(required = false) final String dangerLevel, @RequestParam(required = false) final String corpCode, @RequestParam(required = false) final String gridCode,
                                                                               @RequestParam(required = false) final String checkUnit, @RequestParam(required = false) final Integer state, @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime, @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime,
                                                                               @RequestParam Integer page, @RequestParam Integer pageSize, Integer mobile, Integer queryAll,@RequestParam(required = false)String keyword) {
        MessageBean<DataBean<HiddenDangerDiscovery>> msg = new MessageBean<>();
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LOGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return msg;
        }
        Integer start = null;
        if (page == null || page <= 0) {
            page = 1;
            if (pageSize == null || pageSize <= 0) {
                pageSize = 15;
            }
        }
        start = (page <= 1) ? 0 : (page - 1) * pageSize;
        msg = dangerDiscoveryService.queryDangerByCondition(user, description, dangerType, dangerLevel, corpCode, gridCode, checkUnit, state, startTime, endTime, start, pageSize, mobile,queryAll,submitterCode,keyword);
        if (null != msg.getData())
            msg.getData().setPageNo(page);
        return msg;
    }

    @ApiOperation("隐患台账列表导出接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userCode", value = "当前登录人code,pc不传，app必传字段", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "description", value = "隐患描述", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dangerType", value = "隐患分类", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dangerLevel", value = "隐患分级", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "corpCode", value = "水司code", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "gridCode", value = "网格结点code，隐患所在位置", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "checkUnit", value = "检查单位code", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "检查日期,查询开始日期", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "检查日期，查询结束日期", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "状态,隐患确认之前的状态1:草稿,2:待确认(提交),3:确认,4:驳回", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "exportIds", value = "id数组", dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/export.htm", method = RequestMethod.GET)
    public void export(HttpServletResponse response, @SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String userCode, @RequestParam(required = false) final String description, @RequestParam(required = false) final String dangerType,
                       @RequestParam(required = false) final String dangerLevel, @RequestParam(required = false) final String corpCode, @RequestParam(required = false) final String gridCode,
                       @RequestParam(required = false) final String checkUnit, @RequestParam(required = false) final Integer state, @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime, @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime,@RequestParam(required = false) String exportIds) {
        MessageBean<List<HiddenDangerDiscovery>> msg = new MessageBean<>();
        List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(userCode, null).getData();
        if (null == user) {
            if (null != staffBeanList && staffBeanList.size() > 0) {
                user = staffBeanList.get(0);
            }
        }
        if (null != user) {
            // 模板
            InputStream inputStream = getClass().getClassLoader().getResourceAsStream("static/excel/hiddenDangerDiscovery.xlsx");
            XSSFWorkbook workbook = dangerDiscoveryService.export(user, description, dangerType, dangerLevel, corpCode, gridCode, checkUnit, state, startTime, endTime, inputStream,exportIds);
            if (null != workbook) {
                try (OutputStream os = response.getOutputStream()) {
                    response.setContentType("application/octet-stream");
                    response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("隐患台账列表.xlsx", StandardCharsets.UTF_8));
                    workbook.write(os);
                    os.flush();
                } catch (Exception e) {
                    logger.error(e.getMessage(),e);
                }
            }
        }
    }

    @ApiOperation("隐患台账列表导出接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userCode", value = "当前登录人code,pc不传，app必传字段", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "description", value = "隐患描述", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dangerType", value = "隐患分类", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dangerLevel", value = "隐患分级", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "corpCode", value = "水司code", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "gridCode", value = "网格结点code，隐患所在位置", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "checkUnit", value = "检查单位code", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "检查日期,查询开始日期", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "检查日期，查询结束日期", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "状态,隐患确认之前的状态1:草稿,2:待确认(提交),3:确认,4:驳回", dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/exports.htm", method = RequestMethod.GET)
    public HttpEntity<?> exports(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String userCode, @RequestParam(required = false) final String description, @RequestParam(required = false) final String dangerType,
                                 @RequestParam(required = false) final String dangerLevel, @RequestParam(required = false) final String corpCode, @RequestParam(required = false) final String gridCode,
                                 @RequestParam(required = false) final String checkUnit, @RequestParam(required = false) final Integer state, @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime, @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime) {
        MessageBean<List<HiddenDangerDiscovery>> msg = new MessageBean<>();
        List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(userCode, null).getData();
        if (null == user) {
            if (null != staffBeanList && staffBeanList.size() > 0)
                user = staffBeanList.get(0);
        }
        if (null == user) {
            return null;
        }
        Map<String, Object> map = new HashMap<>();
        msg = dangerDiscoveryService.getAll(user, description, dangerType, dangerLevel, corpCode, gridCode, checkUnit, state, startTime, endTime);
        if (msg.getData() != null) {
            map.put("data", msg.getData());
        } else {
            map.put("data", null);
        }
        File targetFile = new File("static/excel/hiddenDangerDiscoveryTemp.xlsx");
        try {
            InputStream in = getClass().getClassLoader().getResourceAsStream("static/excel/hiddenDangerDiscoveryTemp.xlsx");
            FileUtils.copyInputStreamToFile(in, targetFile);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return Excel.createFile("隐患台账列表", targetFile, "hiddenDangerDiscovery.btl", map);
    }

    @ApiOperation("根据主键获取隐患台账详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "隐患台账id", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/dangerDetails.htm", method = RequestMethod.POST)
    public MessageBean<HiddenDangerDiscovery> queryDangerOne(@RequestParam final String id) {
        return dangerDiscoveryService.queryDangerOne(id);
    }

    @ApiOperation("更新检查单位为空的数据")
    @RequestMapping(value = "/updateCheckUnit.htm", method = RequestMethod.POST)
    public MessageBean<Integer> updateCheckUnit() {
        return dangerDiscoveryService.updateCheckUnit();
    }

    @ApiOperation("根据隐患台账id获取隐患台账的整改列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dangerId", value = "隐患台账id", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/queryRectificationByDangerId.htm", method = RequestMethod.POST)
    public MessageBean<List<HiddenDangerRectification>> queryRectificationByDangerId(@RequestParam final String dangerId) {
        return dangerDiscoveryService.queryRectificationByDangerRecordId(dangerId);
    }

    @ApiOperation("根据隐患台账id删除草稿状态的隐患台账")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "隐患台账id,多个之间用，分开", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/batchDelete.htm", method = RequestMethod.POST)
    public MessageBean<Integer> batchDelete(@RequestParam String ids) {
        List<String> idList = StringUtils.isEmpty(ids) ? null : Arrays.asList(ids.split("[,，]"));
        return dangerDiscoveryService.batchDelete(idList);
    }

    @ApiOperation("保存或提交隐患台账信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userCode", value = "当前登录人code,pc端不传，app必传", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "id", value = "隐患id,新增不传，修改必传", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "corpCode", value = "水司code", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "gridCode", value = "网格结点code，隐患所在位置", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "gridName", value = "网格结点名称，隐患所在位置", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "description", value = "隐患描述", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "checkRecordId", value = "检查记录id,检查记录新增隐患时必填", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "derivation", value = "来源：1安全检查、2随时拍、3隐患台账直接添加、4设备检查", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "dangerCategory", value = "隐患类别，0运营类，1工程类", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "dangerManager", value = "隐患负责人code", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dangerManagerName", value = "隐患负责人名称", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "elementFristType", value = "八要素一级分类,从数据字典类型中取", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "elementSecondType", value = "八要素二级分类,从数据字典类型中取", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dangerType", value = "隐患分类,从指标库中中取", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dangerLevel", value = "隐患分级,从指标库中中取", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "deviceCode", value = "设备/作业编码", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "deviceName", value = "设备/作业名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "discoveryTime", value = "隐患发现时间/检查时间", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "discovererCode", value = "隐患发现人/检查人员code,多个之间用，分开，staffCode_deptCode,staffCode_deptCode", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "discovererDepartment", value = "'隐患发现人/检查人员名称和所在部门名称,多个之间用，分开，staffName_deptName", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "innerStaff", value = "内部违章人员，格式为:staffCode_deptCode,staffCode_deptCode", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "outterStaff", value = "外部违章人员，格式为:外部部门名称_外部违章人员", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "hiddenDangerId", value = "标准隐患id", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "remark", value = "备注", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationType", value = "操作类型，0 保存为草稿，1 提交", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "delFileAddress", value = "要删除的照片的地址，多个之间用；分开", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "keepFileAddress", value = "要保留的照片的地址,多个之间用；分开", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "files", value = "要上传的文件", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "title", value = "提交隐患填写的标题", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "note", value = "提交隐患填写的描述", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "approval", value = "提交隐患选择的审批人,格式为userCode_userId", dataType = "String", paramType = "query"),
            //@ApiImplicitParam(name = "solution", value = "隐患整改措施", required = true, dataType = "String", paramType = "query"),
            //@ApiImplicitParam(name = "rectifier", value = "隐患整改负责人", required = true, dataType = "String", paramType = "query"),
            //@ApiImplicitParam(name = "rectifierName", value = "隐患整改负责人名称", required = true, dataType = "String", paramType = "query"),
            //@ApiImplicitParam(name = "reviewer", value = "隐患整改结果确认人", required = true, dataType = "String", paramType = "query"),
            //@ApiImplicitParam(name = "reviewerName", value = "隐患整改结果确认人名称", required = true, dataType = "String", paramType = "query"),
            // @ApiImplicitParam(name = "deadline", value = "隐患整改期限", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/saveOrCommit.htm", method = RequestMethod.POST)
    @Log(title = "保存或提交隐患台账信息", businessModule = "隐患台账", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<Integer> saveOrCommit(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @ApiIgnore HiddenDangerDiscovery dangerDiscovery,
                                             @RequestParam(required = false) final String title, @RequestParam(required = false) final String note, @RequestParam(required = false) final String approval,
                                             @RequestParam final Integer operationType, String delFileAddress, String keepFileAddress, MultipartFile[] files) {
        MessageBean<Integer> msg = new MessageBean<>();
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LOGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return msg;
        }
        dangerDiscovery.setUpdateUser(user.getName());
        dangerDiscovery.setUpdateTime(new Date());
        dangerDiscovery.setSubmitterCode(user.getCode() + "_" + user.getUserid());
        if (StringUtils.isNotEmpty(dangerDiscovery.getInnerStaff())) {
            String[] arrays = dangerDiscovery.getInnerStaff().split("[,，]");
            List<String> collect = Arrays.asList(arrays).stream().filter(str -> StringUtils.isNotEmpty(str)).collect(Collectors.toList());
            dangerDiscovery.setInnerStaff(new Gson().toJson(collect));
        }
        if (StringUtils.isNotEmpty(dangerDiscovery.getDiscovererCode())) {
            String[] arrays = dangerDiscovery.getDiscovererCode().split("[,，]");
            List<String> collect = Arrays.asList(arrays).stream().filter(str -> StringUtils.isNotEmpty(str)).collect(Collectors.toList());
            dangerDiscovery.setDiscovererCode(new Gson().toJson(collect));
        }
        if (StringUtils.isNotEmpty(dangerDiscovery.getDiscovererDepartment())) {
            String[] arrays = dangerDiscovery.getDiscovererDepartment().split("[,，]");
            List<String> collect = Arrays.asList(arrays).stream().filter(str -> StringUtils.isNotEmpty(str)).collect(Collectors.toList());
            dangerDiscovery.setDiscovererDepartment(new Gson().toJson(collect));
        }
        return dangerDiscoveryService.saveOrCommit(user, dangerDiscovery, operationType, delFileAddress, keepFileAddress, files, title, note, approval);
    }

    @ApiOperation("修改隐患隐患分类，分级等信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "隐患id,新增不传，修改必传", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "elementFristType", value = "一级分类,从数据字典类型中取", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "elementSecondType", value = "二级分类,从数据字典类型中取", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dangerType", value = "隐患分类,从指标库中中取", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dangerLevel", value = "隐患分级,从指标库中中取", dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/update.htm", method = RequestMethod.POST)
    @Log(title = "修改隐患隐患分类，分级等信息", businessModule = "隐患台账", businessManipulation = BusinessManipulation.UPDATE)
    public MessageBean<Integer> update(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam String id, @RequestParam String elementFristType,
                                       @RequestParam String elementSecondType, @RequestParam String dangerType, String dangerLevel) {
        MessageBean<Integer> msg = new MessageBean<>();
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LOGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return msg;
        }
        return dangerDiscoveryService.update(user, id, elementFristType, elementSecondType, dangerType, dangerLevel);
    }

    @ApiOperation("选中多条隐患启动隐患整改流程")
    @ApiImplicitParams({

            @ApiImplicitParam(name = "title", value = "提交隐患填写的标题", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "note", value = "提交隐患填写的描述", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "approval", value = "提交隐患选择的审批人,格式为userCode_userId", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "hiddenDangerIds", value = "选中隐患的id,不同隐患id用，分割", dataType = "String", paramType = "query")
    })
    @Log(title = "启动隐患流程", businessModule = "隐患台账", businessManipulation = BusinessManipulation.INSERT)
    @RequestMapping(value = "/startDangerWorkFlow.htm", method = RequestMethod.POST)
    public MessageBean<Integer> startDangerWorkFlow(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String corpCode, String title, String note, String approval, String hiddenDangerIds) {
        MessageBean<Integer> msg = new MessageBean<>();
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LOGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return msg;
        }
        String[] idArrary = hiddenDangerIds.split("[,，]");
        return dangerDiscoveryService.startDangerWorkFlow(user, corpCode, title, note, approval, idArrary);
    }

    @ApiOperation("填写隐患整改记录，包含整改延期，处理延期申请，整改结果验证,根据operation值区分")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "隐患整改记录id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "hiddenDangeId", value = "隐患id，必填", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "solution", value = "隐患整改措施，operation=0必填", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "rectifier", value = "隐患整改负责人，operation=0必填", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "rectifierName", value = "隐患整改负责人名称，operation=0必填", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "deadline", value = "隐患整改期限，operation=0必填", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "rectificationResult", value = "整改结果，operation=1必填", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "files", value = "上传的附件，operation=1必填", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "completeTime", value = "整改实际完成日期，格式为：yyyy-MM-dd，operation=1必填", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "delayDate", value = "整改延期日期，格式为：yyyy-MM-dd，operation=2必填", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "delayReason", value = "延期理由，operation=2必填", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "refuseDelayReason", value = "拒绝整改延期的理由", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "delayState", value = "操作类型，2:同意延期申请，3拒绝延期", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "reviewResult", value = "验证意见,operation=4必填", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "reviewState", value = "验证类型，0验证不通过，1验证通过", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operation", value = "操作类型，0确认隐患整改人等信息，1填写隐患整改记录，2填写整改延期申请，3处理整改延期申请处理，4整改验证结果", dataType = "int", paramType = "query")
    })
    @Log(title = "保存隐患整改记录信息", businessModule = "隐患台账", businessManipulation = BusinessManipulation.UPDATE)
    @RequestMapping(value = "/updateDangerRectification.htm", method = RequestMethod.POST)
    public MessageBean<Integer> updateDangerRectification(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @ApiIgnore HiddenDangerRectification rectification, Integer operation, MultipartFile[] files, MultipartFile[] supervisionUnitFile, MultipartFile[] rectificationFile) {
        MessageBean<Integer> msg = new MessageBean<>();
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LOGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return msg;
        }
        return dangerDiscoveryService.updateDangerRectification(user, rectification, operation, files, supervisionUnitFile, rectificationFile);
    }

    @ApiOperation("判断是否能够进入下一个审批节点")
    @ApiImplicitParams({

            @ApiImplicitParam(name = "businessIds", value = "审批的businessIds字段内容", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operation", value = "0，确认隐患整改信息判断是否能进入下一审批节点，1填写隐患整改记录/填写隐患整改延期判断是否能进入下一审批节点，2隐患验证判断是否能结束整个流程", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/isAllDealed.htm", method = RequestMethod.POST)
    public MessageBean<Boolean> isAllDealed(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @ApiIgnore Audit audit, Integer operation) {
        MessageBean<Boolean> msg = new MessageBean<>();
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LOGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return msg;
        }
        return dangerDiscoveryService.isAllDealed(user, audit, operation);
    }


    @ApiOperation("审批时点击提交操作，并且操作选中通过时调用该接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "auditId", value = "审批单的id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "cancel", value = "废弃,true", required = true, dataType = "Boolean", paramType = "query")
    })
    @RequestMapping(value = "/updateState.htm", method = RequestMethod.POST)
    public MessageBean<Integer> updateState(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String auditId, Boolean cancel) {
        MessageBean<Integer> msg = new MessageBean<>();
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LOGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return msg;
        }
        return dangerDiscoveryService.updateState(user, auditId, cancel);
    }

//    @ApiOperation("确认是隐患操作")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "id", value = "隐患台账id", required = true, dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "elementFristType", value = "八要素一级分类,从数据字典类型中取", required = true, dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "elementSecondType", value = "八要素二级分类,从数据字典类型中取", required = true, dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "dangerType", value = "隐患分类", required = true, dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "dangerLevel", value = "隐患分级", required = true, dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "innerStaff", value = "内部违章人员，格式为:staffCode_deptCode,staffCode_deptCode", dataType = "int", paramType = "query"),
//            @ApiImplicitParam(name = "outterStaff", value = "外部违章人员，格式为:外部部门名称_外部违章人员", dataType = "int", paramType = "query"),
//            @ApiImplicitParam(name = "solution", value = "隐患整改措施", required = true, dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "rectifier", value = "隐患整改负责人", required = true, dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "rectifierName", value = "隐患整改负责人名称", required = true, dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "reviewer", value = "隐患整改结果确认人", required = true, dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "reviewerName", value = "隐患整改结果确认人名称", required = true, dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "deadline", value = "隐患整改期限", required = true, dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "hiddenOperationType", value = "操作类型，1确认隐患，0关闭流程", required = true, dataType = "int", paramType = "query"),
//            @ApiImplicitParam(name = "processinsId", value = "工作流实例id", required = true, dataType = "String", paramType = "query"),
//    })
//    @RequestMapping(value = "/confirmIsDanger.htm", method = RequestMethod.POST)
//    @Log(title = "确认是隐患操作", businessManipulation = BusinessManipulation.CONFIRM)
//    public MessageBean<String> confirmIsDanger(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @ApiIgnore HiddenDangerDiscovery dangerDiscovery,
//                                               @ApiIgnore HiddenDangerRectification rectification, @RequestParam final Integer hiddenOperationType, @RequestParam final String processinsId) {
//        if (null == user) {
//            MessageBean<String> msg=new MessageBean<>();
//            msg.setCode(BusinessCode.NOT_LOGIN.getCode());
//            msg.setDescription(BusinessCode.NOT_LOGIN.getDescription());
//            return msg;
//        }
//        if (StringUtils.isNotEmpty(dangerDiscovery.getInnerStaff())) {
//            String[] codeArray = dangerDiscovery.getInnerStaff().split("[,，]");
//            List<String> codes = Arrays.asList(codeArray).stream().map(String::trim).collect(Collectors.toList());
//            dangerDiscovery.setInnerStaff(new Gson().toJson(codes));
//        }
//        return dangerDiscoveryService.confirmIsDanger(user, dangerDiscovery, rectification, hiddenOperationType, processinsId);
//    }

//    @ApiOperation("整改负责人填写隐患整改结果")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "id", value = "隐患整改id", required = true, dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "rectificationResult", value = "整改结果", dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "files", value = "上传的附件", dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "completeTime", value = "整改实际完成日期，格式为：yyyy-MM-dd", dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "delayDate", value = "整改延期日期，格式为：yyyy-MM-dd", dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "delayReason", value = "延期理由", dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "rectificateOperationType", value = "操作类型：0填写整改信息，1填写整改延期申请", required = true, dataType = "int", paramType = "query"),
//    })
//    @RequestMapping(value = "/fillInRectification.htm", method = RequestMethod.POST)
//    @Log(title = "整改负责人填写隐患整改结果", businessManipulation = BusinessManipulation.UPDATE)
//    public MessageBean<Integer> fillInRectification(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
//                                                    @ApiIgnore HiddenDangerRectification rectification,@RequestParam final Integer rectificateOperationType, MultipartFile[] files) {
//        if (null == user) {
//            MessageBean<Integer> msg=new MessageBean<>();
//            msg.setCode(BusinessCode.NOT_LOGIN.getCode());
//            msg.setDescription(BusinessCode.NOT_LOGIN.getDescription());
//            return msg;
//        }
//        rectification.setUpdateTime(new Date());
//        rectification.setUpdateUser(user == null ? null : user.getName());
//        return dangerDiscoveryService.fillInRectification(user, rectification,rectificateOperationType, files);
//    }

//    @ApiOperation("整改结果验证人对隐患整改结果验证")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "id", value = "隐患整改id", required = true, dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "reviewResult", value = "验证意见", dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "operationType", value = "操作类型，0 不同意，1 同意", required = true, dataType = "String", paramType = "query"),
//    })
//    @RequestMapping(value = "/confirmRectificationResult.htm", method = RequestMethod.POST)
//    @Log(title = "整改结果验证人对隐患整改结果验证", businessManipulation = BusinessManipulation.CONFIRM)
//    public MessageBean<Integer> confirmRectificationResult(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @ApiIgnore HiddenDangerRectification rectification, @RequestParam final Integer operationType) {
//        if (null == user) {
//            MessageBean<Integer> msg=new MessageBean<>();
//            msg.setCode(BusinessCode.NOT_LOGIN.getCode());
//            msg.setDescription(BusinessCode.NOT_LOGIN.getDescription());
//            return msg;
//        }
//        rectification.setUpdateTime(new Date());
//        rectification.setUpdateUser(user == null ? null : user.getName());
//        return dangerDiscoveryService.confirmRectificationResult(user, rectification, operationType);
//    }

    @ApiOperation("检查记录--根据检查记录id获取隐患列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "checkRecordId", value = "检查记录id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页数", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "int", paramType = "query"),
    })
    @RequestMapping(value = "/queryByCheckRecordId.htm", method = RequestMethod.POST)
    public MessageBean<DataBean<HiddenDangerDiscovery>> queryByCheckRecordId(@RequestParam final String checkRecordId, @RequestParam Integer page, @RequestParam Integer pageSize) {
        Integer start = null;
        if (page == null || page <= 0) {
            page = 1;
            if (pageSize == null || pageSize <= 0) {
                pageSize = 15;
            }
        }
        start = (page <= 1) ? 0 : (page - 1) * pageSize;
        MessageBean<DataBean<HiddenDangerDiscovery>> msg = dangerDiscoveryService.queryDangerByCheckRecordId(checkRecordId, start, pageSize);
        msg.getData().setPageNo(page);
        return msg;
    }

    @ApiOperation("临时隐患列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页数", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "int", paramType = "query"),
    })
    @RequestMapping(value = "/queryTempDanger.htm", method = RequestMethod.POST)
    public MessageBean<DataBean<HiddenDangerDiscovery>> queryTempDanger(Integer page, Integer pageSize) {
        Integer start = null;
        if (page == null || page <= 0) {
            page = 1;
            if (pageSize == null || pageSize <= 0) {
                pageSize = 15;
            }
        }
        start = (page <= 1) ? 0 : (page - 1) * pageSize;
        MessageBean<DataBean<HiddenDangerDiscovery>> msg = dangerDiscoveryService.queryTempDanger(start, pageSize);
        msg.getData().setPageNo(page);
        return msg;
    }

    @ApiOperation("根据整改记录id获取整改记录信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页数", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "int", paramType = "query"),
    })
    @RequestMapping(value = "/queryOneRectificationById.htm", method = RequestMethod.POST)
    public MessageBean<HiddenDangerRectification> queryOneRectificationById(@RequestParam final String rectificationId) {
        return dangerDiscoveryService.queryOneRectificationById(rectificationId);
    }

//    @ApiOperation("启动隐患的确认流程")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "hiddenDangerDiscoveryId", value = "隐患台账id", required = true, dataType = "String", paramType = "query"),
//    })
//    @RequestMapping(value = "/startDangerFlow.htm", method = RequestMethod.POST)
//    public MessageBean<String> startDangerFlow(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,@RequestParam final String hiddenDangerDiscoveryId){
//        MessageBean<String> msg=new MessageBean<>();
//        if (null==user){
//            msg.setCode(BusinessCode.NOT_LOGIN.getCode());
//            msg.setDescription(BusinessCode.NOT_LOGIN.getDescription());
//            return msg;
//        }
//        msg=dangerDiscoveryService.startDangerFlow(user,hiddenDangerDiscoveryId);
//        return msg;
//    }

    @ApiOperation("判断是否为安全管理员")
    @RequestMapping(value = "/isSafetyRole.htm", method = RequestMethod.POST)
    public MessageBean<Boolean> isSafetyRole(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user) {
        return dangerDiscoveryService.isSafetyRole(user);
    }

//    @ApiOperation("处理隐患整改延期申请")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "rectificationId", value = "整改记录id", required = true, dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "refuseDelayReason", value = "拒绝整改延期的理由", dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "dealDelayOperationType", value = "操作类型，0:拒绝延期申请，1同意延期", required = true, dataType = "String", paramType = "query"),
//    })
//    @RequestMapping(value = "/dealDelay.htm", method = RequestMethod.POST)
//   public MessageBean<Integer> dealDelay(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,@RequestParam final String rectificationId,
//                                         @RequestParam(required = false) final String refuseDelayReason,@RequestParam final Integer dealDelayOperationType){
//       MessageBean<Integer> msg=new MessageBean<>();
//       if (null==user){
//           msg.setCode(BusinessCode.NOT_LOGIN.getCode());
//           msg.setDescription(BusinessCode.NOT_LOGIN.getDescription());
//           return msg;
//       }
//       return dangerDiscoveryService.dealDelay(user, rectificationId, refuseDelayReason, dealDelayOperationType);
//   }

    @ApiOperation("根据多个隐患id查询隐患得列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "隐患id，多个之间用，分开", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/queryDangerByIdList.htm", method = RequestMethod.POST)
    public MessageBean<List<HiddenDangerDiscovery>> queryDangerByIdList(String ids) {
        List<String> idList = new ArrayList<>();
        if (StringUtils.isNotEmpty(ids))
            idList = Arrays.asList(ids.split("[,，]"));
        return dangerDiscoveryService.queryDangerByIdList(idList);
    }

    @ApiOperation("某个审批流程中的隐患列表数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "businessIds", value = "流程Audit对应businessIds的值", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/queryDangerByBusinessIds.htm", method = RequestMethod.POST)
    public MessageBean<List<HiddenDangerDiscovery>> queryDangerByBusinessIds(String businessIds) {
        List<String> idList = new ArrayList<>();
        if (StringUtils.isNotEmpty(businessIds))
            idList = JSONObject.parseArray(businessIds, String.class);
        return dangerDiscoveryService.queryDangerByIdList(idList);
    }

    @ApiOperation("导入隐患")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "files", value = "要上传的隐患图片，可上传多个，最多一次性上传10个", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "corpCode", value = "所在单位code", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/importImage.htm", method = RequestMethod.POST)
    public MessageBean<String> importImage(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String corpCode, MultipartFile[] files) {
        MessageBean<String> msg = new MessageBean<>();
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LOGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return msg;
        }
        return dangerDiscoveryService.importImage(user, corpCode, files);
    }


    @ApiOperation("首页工作台隐患列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode", value = "水司code", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "gridCode", value = "网格结点code，隐患所在位置", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "checkUnit", value = "检查单位code", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "检查日期,查询开始日期", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "检查日期，查询结束日期", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "状态,隐患确认之前的状态1:草稿,2:待确认(提交),3:确认,4:驳回", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页数", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "int", paramType = "query"),
    })
    @RequestMapping(value = "/homePageDangerList.htm", method = RequestMethod.POST)
    public MessageBean<DataBean<HiddenDangerDiscovery>> homePageDangerList(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,String userCode, @RequestParam(required = false) final String corpCode, @RequestParam(required = false) final String gridCode,
                                                                     @RequestParam(required = false) final String checkUnit, @RequestParam(required = false) final Integer state, @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
                                                                     @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime, @RequestParam Integer page, @RequestParam Integer pageSize) {
        MessageBean<DataBean<HiddenDangerDiscovery>> msg = new MessageBean<>();
        if (null == user) {
            List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(userCode, null).getData();
            if (null != staffBeanList && staffBeanList.size() > 0) {
                user = staffBeanList.get(0);
            }
        }
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LOGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return msg;
        }
        Integer start = null;
        if (page == null || page <= 0) {
            page = 1;
            if (pageSize == null || pageSize <= 0) {
                pageSize = 15;
            }
        }
        start = (page <= 1) ? 0 : (page - 1) * pageSize;
        msg = dangerDiscoveryService.homePageDangerList(user, corpCode, gridCode, checkUnit, state, startTime, endTime, start, pageSize);
        if (null != msg.getData()) {
            msg.getData().setPageNo(page);
        }
        return msg;
    }


    @ApiOperation("撤回待确认的隐患流程")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "隐患id，", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/withdrawWorkFlow.htm", method = {RequestMethod.GET})
    public MessageBean<String> withdrawWorkFlow(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,String id){
        if(user==null){
            return MessageBean.create(BusinessCode.NOT_LOGIN.getCode(),BusinessCode.NOT_LOGIN.getDescription(),String.class);
        }
        return dangerDiscoveryService.withdrawWorkFlow(user,id);
    }


}

